Json = Json or require("common.Json")
local Util = require("common.Util")
local Config = require("Config")
local Human = require("core.Human")
local Msg = require("core.Msg")
local TencentPayLogic = require("tencentApi.PayLogic")
local TaskMarketHelp = require("tencentApi.TaskMarketHelp")
local RoleDBLogic = require("role.RoleDBLogic")
local ItemDefine = require("bag.ItemDefine")
local EquipExcel = require("excel.Equip")
local EquipQulity = EquipExcel.equipQulity
local StrengthConfig = require("excel.Strength")
local CommonDefine = require("common.CommonDefine")
local MailLogicFW = require("mail.MailLogicFW")
local Grid = require("bag.Grid")
local ServerCommonFW = require("serverCommon.ServerCommonFW")
local Log = require("common.Log")
local DB = require("common.DB")
local LuaMongo = _G.lua_mongo
local FamilyManager = require("family.FamilyManager")
local FamilyLogicFW = require("family.FamilyLogicFW")
local InnerDataDefine = require("innerdata.Define")
local InnerDataManager = require("innerdata.InnerDataManagerFW")
local LogDefine = require("common.LogDefine")
local RoleFFI = require("role.RoleFFI")
local GmCommon = require("chat.GmCommon")
local AdminBroadcast = require("admin.AdminBroadcast")
local Timer = require("core.Timer")
local DailyActFW = require("activity.DailyActFW")
local ActivityExcel = require("excel.Activity")
local DailyActConfig = ActivityExcel.dailyAct
local ActRule = ActivityExcel.dailyActRule
local OpenServerActFW = require("activity.OpenServerActFW")
local OperateActFW = require("activity.OperateActFW")
local MiddleLogic = require("middle.MiddleLogic")
local MiddleOpenDB = require("middle.MiddleOpenDB")
local MPacketDefine = require("middle.MPacketDefine")
local ExchangeLogic = require("fuli.ExchangeLogic")
local BlueLogic = require("tencentApi.BlueLogic")
local PfLogic = require("tencentApi.PfLogic")


local OprOKRet= "{\"result\":1, \"errorMsg\":\"ok\"}"
local UserNotExist= "{\"result\":3, \"errorMsg\":\"User is not exist\"}"
local RoleNameIsNull = "{\"result\":4, \"errorMsg\":\"roleName is null \"}"
adminFunction = {}

function handleAdminRequest(input)
    print("handleAdminRequest input = ", input)
    local oJsonInput = Json.Decode(input)

    if Config.CHECK_AUTH == true then
        --验证
        if _md5(Config.ADMIN_KEY..Config.SVR_INDEX..oJsonInput.method..oJsonInput.unixTime) ~= oJsonInput.sign then
            return "{\"result\":100, \"errorMsg\":\"sign auth failed\"}"
        end
    end

    local handler = adminFunction[oJsonInput.method]
    if handler then
        return handler(oJsonInput, input)
    else
        return adminFunction.robottest(oJsonInput)
    end
    return "{method:" .. oJsonInput.method .. " no handler}"
end

-- 查询帐号是否有角色存在 hasrole
-- 输入: accountName 帐号名
--     ip 用户ip
--     create 是否创建前的查询（为了流失率统计）
-- 输出: hasRole 1-帐号已存在 0-帐号不存在
--     result  1-合法查询 2-传入参赛错误无效查询 3-服务器已满
local hasRoleRet={}
function adminFunction.hasrole(oJsonInput)
    if oJsonInput.accountName == nil or oJsonInput.accountName == "" then
        hasRoleRet.result = 2 -- 传入参数错误
        hasRoleRet.hasRole = 0
        return Json.Encode(hasRoleRet)
    end

    local onlineCnt = 0
    for __ in pairs(Human.onlineHuman) do
        onlineCnt = onlineCnt + 1
    end
    if onlineCnt >= CommonDefine.MAX_ONLINE_COUNT then
        hasRoleRet.result = 3 -- 服务器已满
        hasRoleRet.hasRole = 0
        return Json.Encode(hasRoleRet)
    end

    local newAccount = oJsonInput.accountName
    print("HasRole name query:", newAccount)

    hasRoleRet.result = 1 -- 合法查询
    if RoleDBLogic.isAccountExistInDB(newAccount) then
        hasRoleRet.hasRole = 1
    else
        hasRoleRet.hasRole = 0
        if oJsonInput.create == 1 then
            local userIp = ""
            if oJsonInput.ip ~= nil and oJsonInput.ip ~= "" then
                userIp = oJsonInput.ip
            end
            Log.write(Log.LOGID_OSS_CREATELOSS, newAccount, "", LogDefine.HUMAN_LOST.ENTRANCE, userIp, oJsonInput.pf or "", oJsonInput.app_custom or "")
        end
    end
    return Json.Encode(hasRoleRet)
end

-- 查询角色名是否有角色存在 hasroleByName
-- 输入: roleName 帐号名
-- 输出: hasRole 1-帐号已存在 0-帐号不存在
--     result  1-合法查询 2-传入参赛错误无效查询
local hasRoleByNameRet={}
function adminFunction.hasroleByName(oJsonInput)
    if oJsonInput.roleName == nil or oJsonInput.roleName == "" then
        hasRoleByNameRet.result = 2 -- 传入参数错误
        hasRoleByNameRet.hasRole = 0
        return Json.Encode(hasRoleByNameRet)
    end
    local newName = oJsonInput.roleName
    print("HasRoleByName name query:", newName)

    hasRoleByNameRet.result = 1 -- 合法查询
    if RoleDBLogic.isNameExistInDB(newName) then
        hasRoleByNameRet.hasRole = 1
    else
        hasRoleByNameRet.hasRole = 0
    end
    return Json.Encode(hasRoleByNameRet)
end

-- 创建新角色 createrole
-- 输入: accountName 帐号名
--     roleName 角色名
--     sex 性别
--     ip 用户ip
--     gm gm权限(可以不传) 1-部分gm权限 2-完整gm权限 100-新手引导员
-- 输出: result 1-创建帐号成功 2-传入参数错误 3-角色名字长度不合法 4-角色名含有非法字符 5-角色名已存在 7-账号已有角色存在 8-性别非法 9-职业非法 10-gm权限非法
local createRoleRet = {}
function adminFunction.createrole(oJsonInput)
    if oJsonInput.accountName == nil or oJsonInput.accountName == "" then
        createRoleRet.result = 2 -- -- 传入参数错误
        return Json.Encode(createRoleRet)
    end

    local newName = oJsonInput.roleName
    local nameLen = #newName
    if nameLen < 2 or nameLen > 24 then
        createRoleRet.result = 3 -- -- 角色名字长度不合法
        return Json.Encode(createRoleRet)
    end

    local gm = oJsonInput.gm or "0"
    gm = gm + 0
    if (gm > 2 or gm < 0) and gm ~= 100 then
        createRoleRet.result = 10 -- gm权限非法
        return Json.Encode(createRoleRet)
    end
    if gm == 0 then gm = nil end

    if gm == nil and newName ~= GmCommon.filter_name(newName) then
        createRoleRet.result = 4 -- 角色名含有非法字符
        return Json.Encode(createRoleRet)
    end

    if oJsonInput.sex + 0 > 2 or oJsonInput.sex + 0 < 1 then
        createRoleRet.result = 8 -- 性别非法
        return Json.Encode(createRoleRet)
    end
    local newAccount = oJsonInput.accountName
    if RoleDBLogic.isAccountExistInDB(newAccount) then
        createRoleRet.result = 7 -- 账号已有角色存在
        return Json.Encode(createRoleRet)
    end

    if RoleDBLogic.isNameExistInDB(newName) then
        createRoleRet.result = 5 -- 角色名已存在
        return Json.Encode(createRoleRet)
    end

    local dbTable = RoleDBLogic.createDefaultRole(newAccount, newName, oJsonInput.sex + 0, oJsonInput.pf)
    createRoleRet.result = 1 -- 创建帐号成功

    local userIp = ""
    if oJsonInput.ip ~= nil and oJsonInput.ip ~= "" then
        userIp = oJsonInput.ip
    end

    --print("newAccount:", newAccount, "newName:",newName, "userIp:",userIp, "job:",oJsonInput.job + 0, "sex:",oJsonInput.sex + 0, "leve:",1)
    Log.write(Log.LOGID_OSS_REGISTER,dbTable._id, newAccount, newName, userIp,oJsonInput.sex + 0, 1, oJsonInput.pf or "", oJsonInput.app_custom or "")
    Log.write(Log.LOGID_OSS_CREATELOSS,newAccount, newName, LogDefine.HUMAN_LOST.CREATE_ROLE_FINISH, userIp, oJsonInput.pf or "", oJsonInput.app_custom or "")
    return Json.Encode(createRoleRet)
end
-- 删除角色 deleterole
--     roleName 角色名
-- 输出: result 1-删除角色成功 2-传入参数错误 3-角色名不存在 4-角色当前在线
local deleteRoleRet = {}
function adminFunction.deleterole(oJsonInput)
    if oJsonInput.roleName == nil or oJsonInput.roleName == "" then
        deleteRoleRet.result = 2 -- -- 传入参数错误
        return Json.Encode(deleteRoleRet)
    end

    local roleName = oJsonInput.roleName
    if Human.onlineHuman[roleName] then
        deleteRoleRet.result = 4 -- 角色当前在线
        return Json.Encode(deleteRoleRet)
    end

    local db = RoleDBLogic.getDbByName(roleName)
    if db == nil then
        deleteRoleRet.result = 3 -- 角色名不存在
        return Json.Encode(deleteRoleRet)
    end

    --删号日志
    Log.write(Log.LOGID_OSS_DELETE, db._id, db.account, db.name, db.ip or "",db.sex, db.lv)

    RoleDBLogic.delName(roleName)
    -- 这里还要处理好友 家族 排行榜 -- reyes todo

    deleteRoleRet.result = 1 -- 删除角色成功
    return Json.Encode(deleteRoleRet)
end



lua_vm_info = lua_vm_info or {}
function adminFunction.robottest()
    local oResult = {}
    oResult.online = 0
    oResult.time = os.time()
    oResult.result = 1 --查询成功
    oResult.logic={}
    oResult.vm_mem = lua_vm_info
    oResult.map= {}
    oResult.changeScene = 0
    for k, v in pairs(Human.onlineHuman) do
        oResult.online = oResult.online + 1
        oResult.logic[v.logic_tid] = oResult.logic[v.logic_tid] or 0
        oResult.logic[v.logic_tid] = oResult.logic[v.logic_tid] + 1
        if v.scene_id then
            oResult.map[v.db.map_id] = oResult.map[v.db.map_id] or 0
            oResult.map[v.db.map_id] = oResult.map[v.db.map_id] + 1
        else
            oResult.changeScene = oResult.changeScene + 1
        end
    end
    local msg = Msg.wl.WL_ROBOT_TEST
    msg.type = 1
    for i = 0, 3 do
        Msg.send2logic_id(msg, i)
    end
    return Json.Encode(oResult)
end

function adminFunction.getonlinecount()
    local oResult = {}
    oResult.online = 0
    oResult.time = os.time()
    oResult.result = 1 --查询成功
    oResult.logic={}

    for k, v in pairs(Human.onlineHuman) do
        oResult.online = oResult.online + 1
        oResult.logic[v.logic_tid] = oResult.logic[v.logic_tid] or 0
        oResult.logic[v.logic_tid] = oResult.logic[v.logic_tid] + 1
    end

    return Json.Encode(oResult)
end

function adminFunction.rolebaseinfo(oJsonInput)
    local db = RoleDBLogic.getDbByAccount(oJsonInput.account)
    if not db then
        return UserNotExist
    end
    local oResult = {}
    oResult.result = 1
    oResult.nickname = RoleFFI.ffi_string(db.name)
    oResult.lv = db.lv
    return Json.Encode(oResult)
end

-- 踢特定玩家下线
function adminFunction.useroffline(oJsonInput)
    local name = oJsonInput.roleName
    if name == nil then
        return RoleNameIsNull
    end
    local human = Human.onlineHuman[name]
    if human == nil then
        return UserNotExist
    else
        Human.disconnect(human, CommonDefine.DISCONNECT_KICK_SINGLE)
    end
    return OprOKRet
end

function isCanKick(svrIndex, indexs)
    if not indexs then
        return true
    end
    for i=1,#indexs do
        if svrIndex == indexs[i] + 0 then
            return true
        end
    end 
end

-- 踢所有玩家下线
function adminFunction.alluseroffline(oJsonInput)
    if oJsonInput.svrIndex == nil then
        for __, v in pairs(Human.onlineHuman) do
            Human.disconnect(v, CommonDefine.DISCONNECT_KICK_ALL)
        end    
        Timer.onSaveRank(true)
        FamilyManager.saveAll()
    else
        local svrIndex = oJsonInput.svrIndex 
        for __,v in pairs(Human.onlineHuman) do
            if isCanKick(v.db.svrIndex,svrIndex) then
                 Human.disconnect(v, CommonDefine.DISCONNECT_KICK_ALL)
            end
        end
    end
    return OprOKRet
end


--后台赠送, type:1表示指定人的列表，后面跟names表示所有玩家的名字，2表示在线的所有人，3表示所有人, title, content, grids:{id, cnt}
function adminFunction.sendItem(oJsonInput)
    local gridList = {}
    for i=1, #oJsonInput.grids do
        gridList[i] = Grid.create(nil, oJsonInput.grids[i].id, oJsonInput.grids[i].cnt, 1)
    end
    if oJsonInput.type == 1 then
        for i=1, #oJsonInput.names do
            local human = Human.onlineHuman[oJsonInput.names[i]]
            if not human then
                return UserNotExist
            else
                MailLogicFW.addSystemMessage(human._id, oJsonInput.title, oJsonInput.content, gridList)
            end
        end
    elseif oJsonInput.type == 2 then
        for k in pairs(Human.onlineUuid) do
            MailLogicFW.addSystemMessage(k, oJsonInput.title, oJsonInput.content, gridList)
        end
    elseif oJsonInput.type == 3 then
    end
    return OprOKRet
end


local function setOnlineData(human, ret, count)
    ret[count] = {
        accountName = human.account,
        roleName = human.name,
        level = human.db.lv,
        ip = human.ip,
        onlineTime = os.time() - human.db.lastLoginTime,
        mapID = human.db.map_id,
        lastCG = human.db.lastCG
    }
end
function adminFunction.getonlinelist()
    local ret = {}
    local count = 0
    local ParamErrRet={}

    for k, v in pairs(Human.onlineHuman) do
        count = count +1
        setOnlineData(v, ret, count)
    end

    ParamErrRet.data = ret
    ParamErrRet.result = 1
    ParamErrRet.errorMsg = ""

    return Json.Encode(ParamErrRet)
end

--装备解析器
local function EquipParser(equipment, grid, pos)
    equipment.id = grid.id
    equipment.uuid =  RoleFFI.ffi_string(grid.uuid)
    equipment.count = grid.cnt
    equipment.isBind = grid.bind
    equipment.position = pos
    equipment.quality = grid.data.equip.quality  --品质
    equipment.hole = grid.data.equip.hole --孔数
    equipment.strengthLv = grid.data.equip.strengthLv or 0  --强化等级
    local equip = grid.data.equip
    -- 基础属性
    equipment.baseAttr = {}
    local len = 0
    for k, v in ipairs(EquipExcel.equip[grid.id].baseAttr) do
        len = len + 1
        equipment.baseAttr[len] = {key = v[1], value = v[2] + v[2]*EquipQulity[equipment.quality].attrAddRate,  qualityPercent = EquipQulity[equipment.quality].attrAddRate}
    end
    -- 洗炼属性
    equipment.xiLianAttr = {}
    for i=1, 4 do
        equipment.xiLianAttr[i] = {}
        equipment.xiLianAttr[i].key = equip.xiLianAttr[i-1]
        equipment.xiLianAttr[i].value = equip.xiLianAttrVal[i-1]
        equipment.xiLianAttr[i].star = equip.xiLianStar[i-1]
    end
    --强化属性
    equipment.strengthAttr = {}
    len = 0
    if equip.strengthLv > 0 then
        local strengthenID = EquipExcel.equip[grid.id].strengthenID
        len = #StrengthConfig[strengthenID][equip.strengthLv].addAttrs
        for i=1, #StrengthConfig[strengthenID][equip.strengthLv].addAttrs do
            equipment.strengthAttr[i] = {}
            equipment.strengthAttr[i].key = StrengthConfig[strengthenID][equip.strengthLv].addAttrs[i][1]
            equipment.strengthAttr[i].value = StrengthConfig[strengthenID][equip.strengthLv].addAttrs[i][2]
        end
    end

    len = 0
    equipment.gem = {} --装备镶嵌的宝石
    for i =0, grid.data.equip.hole - 1 do
        len = len + 1
        equipment.gem[len] = grid.data.equip.gems[i]
    end
end

--物品解析器
local function ItemParser(item, grid, pos)
    item.id = grid.id
    item.uuid = RoleFFI.ffi_string(grid.uuid)
    item.count = grid.cnt
    item.isBind = grid.bind
    item.position = pos
end

local function FontAGrid(grid_info, ret, itemLen, pos)
    if grid_info and 0 < grid_info.id and 0 < grid_info.cnt then
        if ItemDefine.isItem(grid_info.id) then --是普通物品
            itemLen.materialLen = itemLen.materialLen + 1
            ret.material[itemLen.materialLen] = {}
            ItemParser(ret.material[itemLen.materialLen], grid_info, pos)
        elseif ItemDefine.isEquip(grid_info.id) then --是装备
            itemLen.equipLen = itemLen.equipLen + 1
            ret.equipment[itemLen.equipLen] = {}
            EquipParser(ret.equipment[itemLen.equipLen], grid_info, pos)
        elseif ItemDefine.isGem(grid_info.id) then --是宝石
            itemLen.gemLen = itemLen.gemLen + 1
            ret.gem[itemLen.gemLen] = {}
            ItemParser(ret.gem[itemLen.gemLen], grid_info, pos)
        end
    end
end

--背包和仓库信息
local function FontGrid(grids, len, ret, itemLen, pos)
    for i = 0, len -1 do
        FontAGrid(grids[i], ret, itemLen, pos)
    end
end
--得到玩家信息/背包/装备
function adminFunction.getuserstatus(oJsonInput)
    local ParamErrRet = {}
    if (oJsonInput.roleName==nil or oJsonInput.roleName == "")
        and (oJsonInput.accountName==nil or oJsonInput.accountName == "") then
        ParamErrRet.result =2
        ParamErrRet.errorMsg = "param error"
        ParamErrRet.data = oJsonInput
        return Json.Encode(ParamErrRet)
    end

    print("oJsonInput.roleNmae:", oJsonInput.roleName)
    print("oJsonInput.accountName:", oJsonInput.accountName)

    local ret = {}
    ret.player = {}     --玩家基本信息
    ret.money = {}      --玩家货币
    ret.equipment = {}    --玩家装备
    ret.gem = {}          --宝石
    ret.material = {}     --普通物品


    local human
    local name
    local bAccount = false
    if oJsonInput.roleName and oJsonInput.roleName ~= "" then
        human = Human.onlineHuman[oJsonInput.roleName]
        name = oJsonInput.roleName
    else
        human = Human.onlineAccount[oJsonInput.accountName]
        name = oJsonInput.accountName
        bAccount = true
    end
    local itemLen = { equipLen = 0, gemLen = 0, materialLen = 0}
    ParamErrRet.result = 1
    if human then
        ret.player.isOnline = 1 --在线
        print("on line")
    else
        print("off line")
        ret.player.isOnline = 0 --不在线

        local humanDb = nil

        if oJsonInput.roleName and oJsonInput.roleName ~= "" then --按角色名查询
            humanDb = RoleDBLogic.getDbByName(oJsonInput.roleName)
        else
            humanDb = RoleDBLogic.loadRole(oJsonInput.accountName)
        end

        print("human:", humanDb)

        if humanDb == nil then --不存在
            print("not exict")
            ParamErrRet.result = 3
            ParamErrRet.errorMsg = "UserNotExist"
            ParamErrRet.data = oJsonInput
            return Json.Encode(ParamErrRet)
        end
        human = {}
        human.db = humanDb
        human.account = human.db.account
        human.name = human.db.name
        human.ip = human.db.ip
        human._id = human.db._id
    end

  
    ret.player.accountName = human.account--账号名
    ret.player.roleName = human.name --角色名
    ret.player.level = human.db.lv --等级
    ret.player.sex = human.db.sex --性别
    ret.player.uuid = human._id --uuid
    ret.player.ip = human.ip --IP
    ret.player.lastLogin = human.db.lastLoginTime --最近登录时间
    ret.player.lastLogout = human.db.lastLogoutTime --最近登出时间
    ret.player.x = human.db.x;
    ret.player.y = human.db.y;
    ret.player.mapid = human.db.map_id
    
    ret.shenbing = {}
    for i=0, human.db.shenbingLen - 1 do
      ret.shenbing[i + 1] = {}
      if human.db.putonShenbing == human.db.shenbing[i].id then
        ret.shenbing[i + 1].status = 1
      else
        ret.shenbing[i + 1].status = 0
      end
      ret.shenbing[i + 1].id = human.db.shenbing[i].id
      ret.shenbing[i + 1].star = human.db.shenbing[i].star
      ret.shenbing[i + 1].lv = human.db.shenbing[i].lv
    end
    
    ret.horse_stage = human.db.horseStageLv
    local horse_lv = math.floor(human.db.horseStarLv / 10) + 1
    if math.floor(human.db.horseStarLv/100) == human.db.horseStageLv then
      horse_lv = horse_lv - 1
    end
    ret.horse_lv = horse_lv
    ret.have_horse = {}    
    for i=0, human.db.haveHorseLen - 1 do
      ret.have_horse[i + 1] = {}
      if human.db.chooseHorseId == human.db.haveHorse[i].haveHorseId then
        ret.have_horse[i + 1].status = 1
      else
        ret.have_horse[i + 1].status = 0
      end
      ret.have_horse[i + 1].id = human.db.haveHorse[i].haveHorseId
      ret.have_horse[i + 1].xx = human.db.haveHorse[i].horseXX
    end
    ret.horse_stage_info = {}
    for i=0, 9 do
      if i < human.db.horseStageLv then
        ret.horse_stage_info[i + 1] = {}
        if human.db.chooseHorseId == i + 1 then
          ret.horse_stage_info[i + 1].status = 1
        else
          ret.horse_stage_info[i + 1].status = 0
        end
        ret.horse_stage_info[i + 1].id = i + 1
        ret.horse_stage_info[i + 1].xx = human.db.horseXX[i]
      end  
    end
    
    ret.pet = {}
    for i=0, human.db.petLen - 1 do
      ret.pet[i + 1] = {}
      if human.db.pet[i].id == human.db.petCombatId then
        ret.pet[i + 1].status = 1
      else
        ret.pet[i + 1].status = 0
      end
      ret.pet[i + 1].id = human.db.pet[i].id
      ret.pet[i + 1].lv = human.db.pet[i].lv
      ret.pet[i + 1].star = human.db.pet[i].star
      ret.pet[i + 1].stage = human.db.pet[i].stage
    end

    ret.money.yuanbao = human.db.yuanbao      --元宝（不绑定）
    ret.money.bind_yuanbao = human.db.bind_yuanbao      --绑定元宝（绑定）
    ret.money.yinliang = human.db.yinliang    --铜币（不绑定）
    ret.money.zhangong = human.db.zhangong    --战功
    ret.money.wushuang = human.db.wushuang      --无双
    ret.player.Fight = human.db.zhandouli    --战斗力
    ret.player.historyYuanbao = human.db.historyYuanbao --历史元宝
    --背包
    FontGrid(human.db.bag, human.db.bagLen, ret, itemLen, 1)
    --仓库
    FontGrid(human.db.store, human.db.storeLen, ret, itemLen, 2)
    --在身上的装备
    FontGrid(human.db.equip, human.db.equipLen, ret, itemLen, 3)

    ParamErrRet.data = ret
    ParamErrRet.errorMsg = ""


    --  print("ret:", Json.Encode(ParamErrRet))

    return Json.Encode(ParamErrRet)
end


--得到玩家基础信息
function adminFunction.getuserbasestatus(oJsonInput)
    local ParamErrRet = {}

    if (oJsonInput.roleName==nil or oJsonInput.roleName == "")
        and (oJsonInput.accountName==nil or oJsonInput.accountName == "") then
        ParamErrRet.result =2
        ParamErrRet.errorMsg = "param error"
        ParamErrRet.data = oJsonInput
        return Json.Encode(ParamErrRet)
    end

    local human
    local name
    local bAccount = false
    if oJsonInput.roleName and oJsonInput.roleName ~= "" then
        human = Human.onlineHuman[oJsonInput.roleName]
        name = oJsonInput.roleName
    else
        human = Human.onlineAccount[oJsonInput.accountName]
        name = oJsonInput.accountName
        bAccount = true
    end

    ParamErrRet.result = 0
    local ret = {}
    if human then     --如果在线
        ParamErrRet.result = 1
        ret.isOnline = 1 --在线
        ret.accountName = human.account --账号名
        ret.roleName = human.name --角色名
        ret.level = human.db.lv --等级
        ret.ip = human.ip --IP
        ret.total_pay = human.db.rmb
        ret.yuanbao = human.db.yuanbao
        ret.bind_yuanbao = human.db.bind_yuanbao
    else --不在线
        local humanDb = nil
        if bAccount == true then
            humanDb = RoleDBLogic.loadRole(name)
        else
            humanDb = RoleDBLogic.getDbByName(name)
        end
        if humanDb then
            --玩家基本信息
            ParamErrRet.result = 1
            ret.accountName = humanDb.account --账号名
            ret.roleName = humanDb.name --角色名
            ret.level = humanDb.lv --等级
            ret.ip = humanDb.ip --IP
            ret.total_pay = humanDb.rmb
            ret.yuanbao = humanDb.yuanbao
            ret.bind_yuanbao = humanDb.bind_yuanbao
            ret.isOnline = 0 --不在线
        end
    end
    ParamErrRet.data = ret
    ParamErrRet.errorMsg = ""
    return Json.Encode(ParamErrRet)
end

function adminFunction.getServerContent(oJsonInput)
    local ParamErrRet={}
    local nData = {} 
    if oJsonInput and oJsonInput.type then
        if oJsonInput.type == 1 then
            nData.curNotice, nData.newNotice = ServerCommonFW.getServerNotice()
            nData.ctlTime = ServerCommonFW.getVersionTime()
            ParamErrRet.result = 1
            ParamErrRet.errorMsg = "ok"
        elseif oJsonInput.type == 2 then
            nData.curVersion, nData.newVersion = ServerCommonFW.getServerVersion()
            nData.ctlTime = ServerCommonFW.getVersionTime()
            ParamErrRet.result = 1
            ParamErrRet.errorMsg = "ok"
        elseif oJsonInput.type == 3 then
            nData = ServerCommonFW.getFirstOpenTime()
            ParamErrRet.result = 1
            ParamErrRet.errorMsg = "ok"
        else
            ParamErrRet.result = 0
            ParamErrRet.errorMsg = "error type"
        end
    else
        ParamErrRet.result = 0
        ParamErrRet.errorMsg = "error args"
    end
    ParamErrRet.data = nData
    return Json.Encode(ParamErrRet)
end

function adminFunction.setServerContent(oJsonInput)
    local ParamErrRet={}
    if oJsonInput and oJsonInput.content and oJsonInput.type then
        if oJsonInput.type == 1 then
            ServerCommonFW.setServerNotice(oJsonInput.content, oJsonInput.ctlTime)
            ParamErrRet.result = 1
            ParamErrRet.errorMsg = "ok"
        elseif oJsonInput.type == 2 then
            ServerCommonFW.setServerVersion(oJsonInput.content, oJsonInput.ctlTime)
            ParamErrRet.result = 1
            ParamErrRet.errorMsg = "ok"
        elseif oJsonInput.type == 3 then
            local ret = pcall(os.date, "*t", oJsonInput.content)
            if not ret then
                ParamErrRet.result = 0
                ParamErrRet.errorMsg = "error time format"
            else
				local oldOpenTime = ServerCommonFW.getFirstOpenTime() 
				if Util.isSameDay2(oldOpenTime, oJsonInput.content) == nil then
					if ServerCommonFW.setFirstOpenTime(oJsonInput.content) == true then
						OpenServerActFW.onInit(true)
						OpenServerActFW.onActCheck()
	                    
						OperateActFW.onInitTodayAct(true)
						OperateActFW.onActCheck()
	                    	                    
						require("middle.MiddleOpenDB").setMiddleOpen()
					end
				end
                ParamErrRet.result = 1
                ParamErrRet.errorMsg = "ok"
            end
        elseif oJsonInput.type == 4 then

        else
            ParamErrRet.result = 0
            ParamErrRet.errorMsg = "error type"
        end
    end
    return Json.Encode(ParamErrRet)
end

itemsLog = nil
local function checkItem(item, response)
    local id = item.id
    local cnt = item.cnt
    local gems = item.gems

    if not ItemDefine.isValidId(id) then
        response.result = 4
        response.msg = "item id invalid"
    end

    if cnt < 1 then
        response.result = 2
        response.msg = "item cnt invalid"
    end

    if not ItemDefine.is_spobj[id] then
        if cnt > ItemDefine.CAP_PER_GRID then
            response.result = 2
            response.msg = "item cnt invalid"
        end
    end

    if ItemDefine.isEquip(id) then -- equip
        if cnt ~= 1 then
            response.result = 2
            response.msg = "item cnt invalid"
        end

        -- check gem id
        local gemIDOK = true
        for _,gemID in pairs(gems) do
            if not ItemDefine.isValidId(gemID) then
                gemIDOK = false
                break
            end
        end

        if not gemIDOK then
            response.result = 5
            response.msg = "gem id invalid"
        end
    end
end

function makeGrid(item, gridList)
    local id = item.id
    local bind = item.bind
    local cnt = item.cnt
    local quality = item.quality
    local strengthenLv = item.strengthenLv

    local gems = item.gems
    local grid ={}
    if ItemDefine.isEquip(id) then -- equip
        Grid.create(grid,id,cnt,bind,quality)
        for i = 1, #gems do
            grid.data.equip.gems[i-1] = gems[i]
        end
        grid.data.equip.strengthLv = strengthenLv
    else
        Grid.create(grid,id,cnt,bind)
    end
    gridList[#gridList + 1] = grid
    itemsLog = itemsLog .. Log.makeGridShort1(grid) .. Log.LINK_FLAG
end

local function addApplyNameList(dbs, name, response)
    local db = RoleDBLogic.getDbByName(name)
    if db then
        dbs[#dbs + 1] = db
    else
        response.result = 7
        response.msg = "roleNameList invalid"
    end
end


local function addApplyAccoutList(dbs, account, response)
    local db = RoleDBLogic.getDbByAccount(account)
    if db then
        dbs[#dbs + 1] = db
    else
        response.result = 7
        response.msg = "roleNameList invalid"
    end
end


local applyGoodsField = {name=1,account=1,lv=1}

function adminFunction.applygoods(oJsonInput)
    local response = {}
    response.result = 1
    local sendType = oJsonInput.sendType
    local mailTitle = oJsonInput.mailTitle
    local mailContent = oJsonInput.mailContent
    local roleNameList = oJsonInput.roleNameList
    local applyID = oJsonInput.applyID

    local items = oJsonInput.items

    if not sendType or sendType < 0 or sendType > 2 then
        response.result = 2
        response.msg = "arg invalid sendType"
        return Json.Encode(response)
    end

    if not mailTitle or mailTitle == "" then
        response.result = 2
        response.msg = "arg invalid mailTitle"
        return Json.Encode(response)
    end

    if not mailContent or mailContent == "" then
        response.result = 2
        response.msg = "arg invalid mailContent"
        return Json.Encode(response)
    end

    if not roleNameList then
        response.result = 2
        response.msg = "arg invalid roleNameList"
        return Json.Encode(response)
    end

    if #items > 7 or #items == 0 then
        response.result = 2
        response.msg = "items len invalid"
        return Json.Encode(response)
    end

    if not applyID then
        response.result = 2
        response.msg = "arg invalid applyID"
        return Json.Encode(response)
    end


    local p_ret, err
    for _,item in ipairs(items) do
        p_ret, err = pcall(checkItem, item, response)
        if not p_ret then
            Log.write(Log.LOGID_ERR_PCALL, "applygoods item.id="..item.id, "item.cnt="..item.cnt,err)
        end
        if  response.result ~= 1 then
            return Json.Encode(response)
        end
    end

    local gridList = {}
    itemsLog = ""
    for _,item in ipairs(items) do
        p_ret, err = pcall(makeGrid, item, gridList)
        if not p_ret then
            Log.write(Log.LOGID_ERR_PCALL, "applygoods item.id="..item.id, "item.cnt="..item.cnt,err)
        end
    end

    if sendType == 0 or sendType == 2 then  -- roleNameList
        local dbs ={}
        for _,name in ipairs(roleNameList) do
            if sendType == 0 then
                p_ret, err = pcall(addApplyNameList, dbs, name, response)
            else
                p_ret, err = pcall(addApplyAccoutList, dbs, name, response)
            end

            if not p_ret then
                Log.write(Log.LOGID_ERR_PCALL, "applygoods name="..name, err)
            end

            if response.result ~= 1 then
                return Json.Encode(response)
            end
        end

        for _,db in ipairs(dbs) do
            p_ret, err = pcall(MailLogicFW.addSystemMessage, db._id,mailTitle,mailContent,gridList)
            if not p_ret then
                Log.write(Log.LOGID_ERR_PCALL, "applygoods id="..db._id, err)
            end
            Log.write(Log.LOGID_OSS_ADMIN,db._id,db.account,db.name,db.lv,applyID,itemsLog)
        end

    else
        local sex = roleNameList.sex
        local startLv = roleNameList.startLv
        local endLv = roleNameList.endLv
        local familyUuid = roleNameList.familyUuid
        local lastLoginTime = roleNameList.lastLoginTime
        local online = roleNameList.online
        if online == 1 then       --只发在线的
            for uuid,human in pairs(Human.onlineUuid) do
                if (sex == 0 or human.db.sex == sex) and (human.db.lv >= startLv and human.db.lv <= endLv) and
                    (familyUuid == "" or familyUuid == RoleFFI.ffi_string(human.db.familyUuid)) and
                    (lastLoginTime == 0 or human.db.lastLoginTime >= lastLoginTime) then
                    p_ret, err = pcall(MailLogicFW.addSystemMessage,uuid,mailTitle,mailContent,gridList)
                    if not p_ret then
                        Log.write(Log.LOGID_ERR_PCALL, "applygoods name="..human.name, err)
                    end
                    Log.write(Log.LOGID_OSS_ADMIN,human._id,human.account,human.name,human.db.lv,applyID,itemsLog)
                end
            end
        elseif online == 0 then     --在线与不在线的都发

            local query = {}
            if sex == 0 then
                query.sex = {["$in"]={1,2}}
            else
                query.sex = sex
            end
            query.lv = {["$gte"]=startLv,["$lte"]=endLv}

            if familyUuid ~= "" then
                query.familyUuid = familyUuid
            end

            if lastLoginTime ~= 0 then
                query.lastLoginTime = {["$gte"]=lastLoginTime}
            end

            LuaMongo.find(DB.db_char,query,applyGoodsField)
            local datas = {}
            local len = 0
            while true do
                local tmp = {}
                if not LuaMongo.next(DB.db_char, tmp) then
                    break
                end
                len = len + 1
                datas[len] = tmp
            end

            for _,data in pairs(datas) do
                p_ret, err = pcall(MailLogicFW.addSystemMessage,data._id,mailTitle,mailContent,gridList)
                if not p_ret then
                    Log.write(Log.LOGID_ERR_PCALL, "applygoods name="..data.name, err)
                end
                Log.write(Log.LOGID_OSS_ADMIN,data._id,data.account,data.name,data.lv,applyID,itemsLog)
            end
        end
    end

    response.msg = "applygoods ok"
    return Json.Encode(response)
end

--发邮件
function adminFunction.mail(oJsonInput)
    local response = {}
    response.result = 1
    if oJsonInput.scope.startLv == nil or oJsonInput.scope.endLv == nil then
        response.result = 3
        response.msg =" startLv or endLv error"
        return Json.Encode(response)
    end
    if oJsonInput.all == 1 and oJsonInput.scope.outCondition == nil then
        response.result = 3
        response.msg =" outCondition error"
        return Json.Encode(response)
    end
    local startLv = oJsonInput.scope.startLv
    local endLv = oJsonInput.scope.endLv
    local successCount = 0
    local failCount = 0
    local p_ret, err
    if oJsonInput.all == 1 then -- 发送给全部在线
        if oJsonInput.scope.outCondition == 2 then
            for k, v in pairs(Human.onlineUuid) do
                if v.db.lv >= startLv and v.db.lv <= endLv then
                    p_ret, err = pcall(MailLogicFW.addSystemMessage, v._id,oJsonInput.title,oJsonInput.content)
                    if p_ret then
                        successCount = successCount + 1
                    else
                        failCount = failCount + 1
                        Log.write(Log.LOGID_ERR_PCALL, "mail rolename="..v.name, err)
                    end
                end
            end
        else
            local query = {}
            query.lv = {["$gte"]=startLv,["$lte"]=endLv}
            LuaMongo.find(DB.db_char,query,applyGoodsField)
            local datas = {}
            local len = 0
            while true do
                local tmp = {}
                if not LuaMongo.next(DB.db_char, tmp) then
                    break
                end
                len = len + 1
                datas[len] = tmp
            end
            for _,data in pairs(datas) do
                p_ret, err = pcall(MailLogicFW.addSystemMessage,data._id,oJsonInput.title,oJsonInput.content)
                if not p_ret then
                    failCount = failCount + 1
                    Log.write(Log.LOGID_ERR_PCALL, "applygoods name="..data.name, err)
                else
                    successCount = successCount + 1
                end
            end
        end
    elseif oJsonInput.roleNameList then
        for i=1,#oJsonInput.roleNameList do
            local db = RoleDBLogic.getDbByName(oJsonInput.roleNameList[i])
            if db and db.lv >=startLv and db.lv <= endLv then
                p_ret, err = pcall(MailLogicFW.addSystemMessage, db._id,oJsonInput.title,oJsonInput.content)
                if p_ret then
                    successCount = successCount + 1
                else
                    failCount = failCount + 1
                    Log.write(Log.LOGID_ERR_PCALL, "mail rolename="..db.name, err)
                end
            else
                failCount = failCount + 1
            end
        end
    end
    if failCount == 0 then
        response.result = 1
    else
        response.result = 2
    end
    response.successCount = successCount
    response.failCount = failCount
    return Json.Encode(response)
end


-- 取家族信息 by 家族名
function adminFunction.findFamilyByName(oJsonInput)
    local familyName = oJsonInput.familyName
    local response={}
    if not familyName or type(familyName) ~= "string" or #familyName == 0 then
        response.result = 2
        response.msg = "familyName invalid"
        return Json.Encode(response)
    end

    local family = FamilyManager.findByFamilyName(familyName)
    if not family then
        response.result = 3
        response.msg = "family not exist"
        return Json.Encode(response)
    end

    response.familyUuid = family._id
    response.result = 1
    response.msg = "family find ok"
    return Json.Encode(response)
end


function adminFunction.destoryfamily(oJsonInput)
    local familyName = oJsonInput.familyName
    local family = FamilyManager.findByFamilyName(familyName)
    local msg = ""
    local response = {}
    if family then
        local retCode = FamilyLogicFW.kickallmember(family)
        response.result = retCode
        if retCode == 0 then
            msg = "ok"
            --elseif retCode == 3 then
            --	msg = "not destory in mwbd"
            --elseif retCode == 4 then
            --	msg = "not destory in family war"
        else
            msg = "error"
        end
    else
        response.result = 2
        msg = "family name invalid"
    end

    response.msg = msg
    return Json.Encode(response)
end

function adminFunction.updateYuanbao(oJsonInput)
    local ParamErrRet = {}

    if (oJsonInput.roleName==nil or oJsonInput.roleName == "")
        and (oJsonInput.accountName==nil or oJsonInput.accountName == "") then
        ParamErrRet.result =2
        ParamErrRet.errorMsg = "param error:name err"
        ParamErrRet.data = oJsonInput
        return Json.Encode(ParamErrRet)
    end

    local moneyType = oJsonInput.MoneyType
    local moneyCount = oJsonInput.MoneyCount
    if not moneyCount then
        ParamErrRet.result =2
        ParamErrRet.errorMsg = "param error:moneyCount err"
        ParamErrRet.data = oJsonInput
        return Json.Encode(ParamErrRet)
    end

    local human
    local name
    local bAccount = false
    if oJsonInput.roleName and oJsonInput.roleName ~= "" then
        human = Human.onlineHuman[oJsonInput.roleName]
        name = oJsonInput.roleName
    else
        human = Human.onlineAccount[oJsonInput.accountName]
        name = oJsonInput.accountName
        bAccount = true
    end

    ParamErrRet.result = 0
    local ret = {}

    if human then			--如果在线
        ParamErrRet.result = 0
        ret.accountName = RoleFFI.ffi_string(human.db.account) --账号名
        ret.roleName = RoleFFI.ffi_string(human.db.name) --角色名
        if moneyType == 1 then
            ret.oldMoneyCount = human.db.yuanbao
            local newMoneyCount = human.db.yuanbao + moneyCount
            if newMoneyCount >= 0 then
                InnerDataManager.Send2LInnerData(human, InnerDataDefine.INNERDATA_TYPE_ROLE, {type = 1, updateYuanbao = moneyCount, logtype = "gm"})
            else
                ParamErrRet.result = 4
                ParamErrRet.errorMsg = "after update,yuanbao < 0"
            end
            ret.newMoneyCount = newMoneyCount
            ret.moneyType = moneyType
        else
            ret.oldMoneyCount = human.db.bind_yuanbao
            local newMoneyCount = human.db.bind_yuanbao + moneyCount
            if newMoneyCount >= 0 then
                InnerDataManager.Send2LInnerData(human, InnerDataDefine.INNERDATA_TYPE_ROLE, {type = 2, updateYuanbao = moneyCount, logtype = "gm"})
            else
                ParamErrRet.result = 5
                ParamErrRet.errorMsg = "after update,bind_yuanbao < 0"
            end
            ret.newMoneyCount = newMoneyCount
            ret.moneyType = moneyType
        end
    else --不在线
        ParamErrRet.result = 3
        ParamErrRet.errorMsg = "user no online"
        ParamErrRet.data = oJsonInput
        return Json.Encode(ParamErrRet)
    end
    ParamErrRet.data = ret
    ParamErrRet.errorMsg = ""
    return Json.Encode(ParamErrRet)
end

function adminFunction.OnTotalVipInfoReturn(oJsonInput)
  return TencentPayLogic.OnTotalVipInfoReturn(oJsonInput)
end

function adminFunction.OnBlueVipInfoReturn(oJsonInput)
  return BlueLogic.OnBlueVipInfoReturn(oJsonInput)
end


function adminFunction.OnYellowDeliverReturn(oJsonInput)
  return BlueLogic.OnYellowDeliverReturn(oJsonInput)
end

function adminFunction.OnTokenReturnForBuyGood(oJsonInput)
    return TencentPayLogic.OnTokenReturnForBuyGood(oJsonInput)
end

function adminFunction.OnTokenReturnForOpenVip(oJsonInput)
    return BlueLogic.OnTokenReturnForOpenVip(oJsonInput)
end

function adminFunction.OnTencentDeliverReturn(oJsonInput)
    local token = oJsonInput.token
    local billno = oJsonInput.billno
    local payitem = oJsonInput.payitem
    local openid = oJsonInput.openid
    local zoneid = oJsonInput.zoneid
    local amt = oJsonInput.amt
    local payamt_coins = oJsonInput.payamt_coins
    local ts = oJsonInput.ts
    local acct = oJsonInput.acct_payamt_coins

    local response = {}

    if (payamt_coins == nil) then
        payamt_coins = 0
    end

    if (token == nil or billno == nil or payitem == nil or
        openid == nil or zoneid == nil) then
        response.ret = "4"
        response.msg = "Invalid paramter: not all param pass to server"
        return Json.Encode(response)
    end
    -- TODO 写充值日志
    -- TODO 处理解析payitem
    local result = TencentPayLogic.OnTencentDeliverReturn(token, billno, payitem, zoneid,
    amt, payamt_coins,ts,acct)
    if (result == nil) then
        response.ret = "5"
        response.msg = "Deliver function return nil"
        return Json.Encode(response)
    end
    response.ret = result.ret
    response.msg = result.msg
    return Json.Encode(response)

end


function adminFunction.OnInformTaskCompletedReturn(oJsonInput)
  local response = {}
  response.ret = 1
  response.msg = "OK"
  return Json.Encode(response)
end


function adminFunction.onCheck(oJsonInput)
  local response = {}
  local result = TaskMarketHelp.onCheck(oJsonInput)
    response.ret = result.ret
    response.msg = result.msg
    return Json.Encode(response)
end

function adminFunction.onCheckAward(oJsonInput)
  local response = {}
  local result = TaskMarketHelp.onCheckAward(oJsonInput)
  response.ret = result.ret
  response.msg = result.msg
  return Json.Encode(response)
end

function adminFunction.onAward(oJsonInput)
  local response = {}
  local result = TaskMarketHelp.onAward(oJsonInput)
  response.ret = result.ret
  response.msg = result.msg
  return Json.Encode(response)
end


--即时发送
function adminFunction.broadcast(oJsonInput)
    --print("broadcast:", "oJsonInput.type:",oJsonInput.type, "oJsonInput.msg:", oJsonInput.msg)
    local ParamErrRet={}
    if oJsonInput.type == nil or oJsonInput.type + 0 < 0 or oJsonInput.msg == nil then
        ParamErrRet.result = 2
        ParamErrRet.errorMsg = " param error"
        ParamErrRet.data = oJsonInput
        return Json.Encode(ParamErrRet)
    end
    local type = oJsonInput.type + 0
    ParamErrRet.result = 1
    ParamErrRet.msg = "broadcast ok"
    AdminBroadcast.DoBroadcast(type, oJsonInput.msg)
    return Json.Encode(ParamErrRet)
end
--循环间隔发送
function adminFunction.configbroadcast(oJsonInput)
    local ParamErrRet={}
    if oJsonInput.id == nil or
        oJsonInput.action == nil or oJsonInput.action+0<1 or oJsonInput.action+0>3 or
        (oJsonInput.action+0 ~= 3 and
        (oJsonInput.type == nil or oJsonInput.type+0<0 or
        oJsonInput.content == nil or oJsonInput.id == nil or oJsonInput.id+0<0 or
        oJsonInput.beginDate == nil or oJsonInput.endDate== nil or
        oJsonInput.beginTime == nil or oJsonInput.endTime== nil or
        oJsonInput.interval  == nil or oJsonInput.interval+0 <=0)) then
        ParamErrRet.result = 2
        ParamErrRet.errorMsg = " param error"
        ParamErrRet.data = oJsonInput
        return Json.Encode(ParamErrRet)
    end
    --local curDate = os.date("%Y%m%d", os.time())
    local curDateTime = os.time()
    if oJsonInput.action+0 ~=3 and oJsonInput.endDate+0 < curDateTime then
        ParamErrRet.result = 2
        ParamErrRet.errorMsg = " param error: endDate < current Date"
        ParamErrRet.data = nil
        return Json.Encode(ParamErrRet)
    end

    local action = oJsonInput.action + 0
    if action == 1 then
        AdminBroadcast.AddBroadcast(oJsonInput.id, oJsonInput.type+0,
        oJsonInput.beginDate+0, oJsonInput.endDate+0,
        oJsonInput.beginTime+0, oJsonInput.endTime+0,
        oJsonInput.interval+0, oJsonInput.content)
    elseif action == 2 then
        AdminBroadcast.ModifyBroadcast(oJsonInput.id, oJsonInput.type+0,
        oJsonInput.beginDate+0, oJsonInput.endDate+0,
        oJsonInput.beginTime+0, oJsonInput.endTime+0,
        oJsonInput.interval+0, oJsonInput.content)
    elseif action == 3 then
        AdminBroadcast.DelBroadcast(oJsonInput.id)
    end
    ParamErrRet.result = 1
    ParamErrRet.msg = "broadcast ok"
    return Json.Encode(ParamErrRet)
end

local err1 = Json.Encode({result = 1, msg = "ban_say_ok"})
local err2 = Json.Encode({result = 2, msg = "name not exist"})
local fields = {ban_say_time = 1}
function adminFunction.ban_say(m)
    local db = RoleDBLogic.getDbByName(m.name, fields)
    if not db then
        return err2
    end
    db.ban_say_time = Timer.now + m.minute * 60 * 1000
    if not Human.onlineHuman[m.name] then
        RoleDBLogic.saveRoleSset(db)
    else
        Human.onlineHuman[m.name].db.ban_say_time = db.ban_say_time
    end
    return err1
end

function adminFunction.getActList(oJsonInput)
    local ParamErrRet={}
    local nReturnActList = {}
    for nType, v in pairs(DailyActFW.DailyActList) do
        nReturnActList[nType] = nReturnActList[nType] or {}
        for nActConfigID, nActList in pairs(v._configList) do
            local nActConfigData = DailyActConfig[nActConfigID]
            if nActConfigData then
                if not nReturnActList[nType][nActConfigID] then
                    nReturnActList[nType][nActConfigID] = {}
                    nReturnActList[nType][nActConfigID]._actList = {}
                end
                local nActData = nReturnActList[nType][nActConfigID]
                nActData.name = nActConfigData.name

                for actNum, actArgs in pairs(nActList) do
                    local nRuleData = ActRule[actArgs.ruleid]
                    if nRuleData then
                        if not nActData._actList[actArgs.hour] then
                            nActData._actList[actArgs.hour] = {}
                        end
                        local nTempData = nActData._actList[actArgs.hour]
                        nTempData.min = actArgs.min
                        nTempData.static = DailyActFW.onGetActStatus(actArgs.type, actNum, actArgs.hour, actArgs.min)
                        nTempData.gap = nRuleData.gap
                        nTempData.condition = {}
                        for nConditonType, nConditonData in pairs(nRuleData.condition) do
                            nTempData.condition[nConditonType] = nConditonData
                        end
                        nTempData.args = {}
                        for nArgType, nArgData in pairs(nRuleData.args) do
                            nTempData.condition[nArgType] = nArgData
                        end
                        nTempData.reward = {}
                        for nRewardType, nRewardData in pairs(nRuleData.item) do
                            if not nTempData.reward[nRewardType] then
                                nTempData.reward[nRewardType] = {}
                            end
                            for nIndex, nRewardItem in ipairs(nRewardData) do
                                nTempData.reward[nRewardType][nIndex] = nRewardItem
                            end
                        end
                    end
                end
            end
        end
    end
    ParamErrRet.data = nReturnActList
    ParamErrRet.result = 1
    ParamErrRet.errorMsg = "ok"
    return Json.Encode(ParamErrRet)
end

function adminFunction.gmAddAct(oJsonInput)
    local ParamErrRet={}
    if not oJsonInput or not oJsonInput.actNum or not oJsonInput.startHour or not oJsonInput.startMin or not oJsonInput.ruleID or not oJsonInput.status then
        ParamErrRet.result = -1
        ParamErrRet.msg = "error args"
        return
    else
        local nResult = DailyActFW.onAddAct(oJsonInput.actNum, oJsonInput.startHour, oJsonInput.startMin, oJsonInput.ruleID, oJsonInput.status)
        ParamErrRet.result = (nResult == true and 0 or -2)
        ParamErrRet.msg = (nResult == true and "add act success" or "add act failed")
    end
    return Json.Encode(ParamErrRet)
end

function adminFunction.gmEndAct(oJsonInput)
    local ParamErrRet={}
    if not oJsonInput or not oJsonInput.actNum then
        ParamErrRet.result = -1
        ParamErrRet.msg = "error args"
        return
    else
        DailyActFW.onEndAct(oJsonInput.actNum)
        ParamErrRet.result = 0
        ParamErrRet.msg = ""
    end
    return Json.Encode(ParamErrRet)
end

function adminFunction.gmActCtl(oJsonInput)
    local ParamErrRet={}
    if not oJsonInput or not oJsonInput.actConfigID or not oJsonInput.actNum or not oJsonInput.static or oJsonInput.static > 1 or oJsonInput.static < 0 then
        ParamErrRet.result = -1
        ParamErrRet.msg = "error args"
        return
    else
        DailyActFW.onGMCtlAct(oJsonInput.actConfigID, oJsonInput.actNum, tonumber(oJsonInput.static))
        ParamErrRet.result = 0
        ParamErrRet.msg = ""
    end
    return Json.Encode(ParamErrRet)
end

function adminFunction.setmiddledb(oJsonInput)
  local middleOpenDB = oJsonInput.middleOpenDB
  if middleOpenDB == 1 then
    MiddleOpenDB.setMiddleOpen(true)
  else
    MiddleOpenDB.setMiddleOpen(nil)
  end

  local response = {}
  response.result = 1
  response.msg = "set middle open db ok"
  if MiddleOpenDB.isMiddleOpen() == true then
    response.middleOpenDB = 1
  else
    response.middleOpenDB = 0
  end
  return Json.Encode(response)
end

function adminFunction.getmiddle(oJsonInput)  --得到当前跨服状态
  local response = {}
  response.result = 1
  response.msg = "get middle open ok"
  if MiddleLogic.ENABLE_MIDDLE == true then
    response.middleOpen = 1
  else
    response.middleOpen = 0
  end
  return Json.Encode(response)
end

function adminFunction.setmiddle(oJsonInput)  -- 设置跨服开关
  local middleOpen = oJsonInput.middleOpen
  if middleOpen == 1 then
    MiddleLogic.ENABLE_MIDDLE = true
  else
    MiddleLogic.ENABLE_MIDDLE = false
  end

  local response = {}
  response.result = 1
  response.msg = "get middle open ok"
  if MiddleLogic.ENABLE_MIDDLE == true then
    response.middleOpen = 1
  else
    response.middleOpen = 0
  end
  return Json.Encode(response)
end

function adminFunction.kickMiddle(oJsonInput)
  _G.collectgarbage("step", 100000)

  local fields = {
    middleFlag=1,
    account=1,
    name=1,
  }
  local funset = {middleFlag = 1}

  local response = {}
  response.result = 1
  response.msg = "ok"
  if not Config.IS_MIDDLE then
    response.result = 2
    response.msg = "this is not middle svr"
    return Json.Encode(response)
  end
  
  local svrIndex = oJsonInput.svrIndex
  
  for k, v in pairs(Human.onlineUuid) do
    if v and (not svrIndex or isCanKick(v.db.svrIndex,svrIndex)) then
      response.result = 3
      response.msg = "has online user pl kick all first "
      return Json.Encode(response)    
    end
  end
  
  for uuid, loginData in pairs(MiddleLogic.NEED_LOGIN_DATA) do
    if not svrIndex or isCanKick(loginData.svrIndex,svrIndex) then
        local fd = MiddleLogic.getFDBySvrIndex(loginData.svrIndex)
        if fd then
          _G.msg_middle_parse.writebegin(fd)
          _G.msg_middle_parse.writeint(MPacketDefine.M2G_LOGIN_MIDDLE_TIMEOUT)
          _G.msg_middle_parse.writestring(uuid)
          _G.msg_middle_parse.writeend()
          
          local targetDB = RoleDBLogic.getDbByUuid(uuid, fields)
          if targetDB then
            targetDB.middleFlag = 0
            RoleDBLogic.saveRoleSset(targetDB, funset)
            Log.write(Log.LOGID_OSS_MIDDLE, uuid, targetDB.account, targetDB.name, LogDefine.MIDDLE_ACTION.SET_MIDDLE_FLAG_0_ADMIN)
          end
          
          MiddleLogic.NEED_LOGIN_DATA[uuid] = nil
        else
          response.result = 4
          response.msg = "can not get fd by svrIndex:" .. loginData.svrIndex
          return Json.Encode(response)
        end
    end
  end
  
  LuaMongo.find(DB.db_char, {})
  while true do
    local db = {}
    if not LuaMongo.next(db) then
      break
    end
    
    if db.middleFlag == 1 then
      -- 向正常服发送M2G_LOGOUT_MIDDLE_DATA
      if not svrIndex or isCanKick(db.svrIndex,svrIndex) then
          local fd = MiddleLogic.getFDBySvrIndex(db.svrIndex)
          if fd then
            _G.msg_middle_parse.writebegin(fd)
            _G.msg_middle_parse.writeint(MPacketDefine.M2G_LOGOUT_MIDDLE_DATA)
            _G.msg_middle_parse.writeint(db.svrIndex)
            _G.msg_middle_parse.writetable(db)
            _G.msg_middle_parse.writeend()
            
            print("admin kick middle dirty data:", db.account)
          end
      end
    end
  end
  
  print("admin kick middle end")
  return Json.Encode(response)
end

-- 确认跨服服已经没有玩家了
-- result 1:safe 2:has user in this middle svr 
function adminFunction.makesuremiddle(oJsonInput)
  local response = {}
  response.result = 1
  response.msg = "safe no user in middle svr"
  
  local svrIndex = oJsonInput.svrIndex 
  for k, v in pairs(Human.onlineUuid) do
    if v and (not svrIndex or isCanKick(v.db.svrIndex,svrIndex)) then
      response.result = 2
      response.msg = "has online user account:" .. v.account .. " svrIndex:" .. v.db.svrIndex
      return Json.Encode(response)    
    end
  end
  
  LuaMongo.find(DB.db_char, {})
  while true do
    local data = {}
    if not LuaMongo.next(data) then
      break
    end
    if data.middleFlag == 1 then
      if not svrIndex or isCanKick(data.svrIndex,svrIndex) then
          local fd = MiddleLogic.getFDBySvrIndex(data.svrIndex)
          if fd then
            response.result = 2
            response.msg = "has offline user account:" .. data.account .. " svrIndex:" .. data.svrIndex
            return Json.Encode(response)
          end
      end
    end
  end
  return Json.Encode(response)
end

function adminFunction.OnCheckActivateReturn(oJsonInput)
	local ret = ExchangeLogic.OnCheckActivateReturn(oJsonInput)
	return Json.Encode(ret)
end

function adminFunction.OnSetActivateReturn(oJsonInput)
	local ret = ExchangeLogic.OnSetActivateReturn(oJsonInput)
	return Json.Encode(ret)
end

function adminFunction.middleSyncFamilyData(oJsonInput)
  local response = {}
  if Config.IS_MIDDLE then
    require("middle.MiddleFamilySign").syncFamilyWarData()   
    response.result = 1
    response.msg = "middle sync family war data ok.."
  else 
    response.result = 2
    response.msg = " not middle server"
  end
  return Json.Encode(response)
end

function adminFunction.middleFamilyDataQuery(oJsonInput)
  local response = {}
  if Config.IS_MIDDLE then
      local data = require("middle.MiddleFamilySign").FAMILY_WAR_SIGN_DATA
      response.sign ={}
      local len = 0
      for k, v in pairs(data) do
          len = len + 1
          response.sign[len] = {uuid= k, rank=v.rank, name=v.name}
      end
      
      data = require("middle.MiddleFamilySign").FAMILY_WAR_DATA
      response.war = {}
      
      for k,v in pairs(data) do
          len = len + 1
          response.war[len] = {uuid= v.uuid, rank=v.rank, name=v.name}
      end
      response.msg= "ok"
  else
      response.result = 2
      response.msg = " not middle server"
  end   
  return Json.Encode(response) 
end


----联运充值回调
--account,order,amt,xianshiCnt,ts
function adminFunction.onLianyunPayCallback( oJsonInput , gm)
  local account = oJsonInput.account
  local order = oJsonInput.order
  local amt = oJsonInput.amt
  local xianshiCnt = oJsonInput.xianshiCnt
  local ts = oJsonInput.ts

  local response = {}
  if account == nil or account == "" 
    or order == nil or order == ""
    or amt == nil or amt == "" or amt + 0  <= 0
    or xianshiCnt == nil or xianshiCnt == "" or amt + 0 <= 0 then

    response.ret =  9
    response.msg = "param error"
    return Json.Encode(response)
  end


  if not RoleDBLogic.isAccountExistInDB(account) then

    response.ret =  2
    response.msg = "account " ..  account .. " not exist"
    return Json.Encode(response)
  end
  amt = amt + 0
  response.ret, response.msg = TencentPayLogic.onLianyunPay(account,order,amt*100,xianshiCnt+0,ts, gm)
  return Json.Encode(response)
end

function adminFunction.getFamilyByName(oJsonInput)  
  local ParamErrRet = {}
  ParamErrRet.result = 1
  ParamErrRet.msg = "ok"  
  local familyName = oJsonInput.familyName
  local family = FamilyManager.findByFamilyName(familyName)
  if not family then
    ParamErrRet.result = 2
    ParamErrRet.msg = "family not exist"
    return Json.Encode(ParamErrRet) 
  end
  
  local copyFamily = {}
  Util.copyTable(family,copyFamily)
  ParamErrRet.family = copyFamily
  return Json.Encode(ParamErrRet)  
end

